/** \file
* Implementation of the curl globals class.
* This file is part of Chorus, available at
* http://code.google.com/p/chorus-twitter/ . This file and all associated files
* and derivative works are bound by the terms of the LGPL 3.0 license,
* available at http://www.gnu.org/licenses/lgpl-3.0-standalone.html .
* \par Subversion URL:
* \$URL: http://chorus-twitter.googlecode.com/svn/branches/cpp/src/system/CurlGlob.cpp $
* \version \$Rev: 152 $
* \date    \$Date: 2010-04-06 07:35:13 +0000 (Tue, 06 Apr 2010) $
*/

#include "config.h"

#include "system/DebugConsole.hpp"
#include "system/CurlGlob.hpp"

CurlGlob::CurlGlob()
{
	CURLcode eresult;
	if (eresult = curl_global_init(CURL_GLOBAL_ALL))
	{
		PDEBUG_CURL("curl_global_init failed", eresult);
		return;
	}
	curlshare = curl_share_init();
	if (!curlshare)
	{
		PDEBUG("curl_share_init failed");
		return;
	}

	CURLSHcode result;
	if (result = curl_share_setopt(curlshare, CURLSHOPT_SHARE,
		CURL_LOCK_DATA_COOKIE))
	{
		PDEBUG_CURL("curl_share_setopt failed", result);
		return;
	}
	if (result = curl_share_setopt(curlshare, CURLSHOPT_SHARE,
		CURL_LOCK_DATA_DNS))
	{
		PDEBUG_CURL("curl_share_setopt failed", result);
		return;
	}
}

CurlGlob::~CurlGlob()
{
	if (curlshare)
	{
		CURLSHcode result = curl_share_cleanup(curlshare);
		if (result)
			PDEBUG_CURL("curl_share_cleanup failed", result);
		curlshare = 0;
	}
	
	curl_global_cleanup();
}

void CurlGlob::lockCallback(CURL *handle, curl_lock_data data,
	curl_lock_access access, void *userptr)
{
	((CurlGlob*)userptr)->lockData(data);
}

void CurlGlob::lockData(curl_lock_data data)
{
	datamutexes[data].lock();
}

void CurlGlob::unlockCallback(CURL *handle, curl_lock_data data,
	void *userptr)
{
	((CurlGlob*)userptr)->unlockData(data);
}

void CurlGlob::unlockData(curl_lock_data data)
{
	datamutexes[data].unlock();
}
